package com.hmdp.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.common.Constants;
import com.hmdp.dto.UserDTO;
import com.hmdp.utils.UserHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RequiredArgsConstructor
@Component
public class ReflushInterceptor implements HandlerInterceptor {

    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取token
        String token = request.getHeader("authorization");
        // 判断token是否存在
        if (StrUtil.isBlank(token)) {
            return true;
        }

        String key = Constants.USER_LOGIN_TOKEN_PREFIX + token;
        Map<Object, Object> user = stringRedisTemplate.opsForHash().entries(key);

        if (user.isEmpty()) {
            return true;
        }

        UserDTO userDTO = BeanUtil.fillBeanWithMap(user, new UserDTO(), true);
        UserHolder.saveUser(userDTO);
        //每次有请求，就刷新token的时间
        stringRedisTemplate.expire(key, Constants.LOGIN_USER_TTL, TimeUnit.MINUTES);

        return true;
    }
}
